package com.example.uibestprac

import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.listviewtest.databinding.MsgLeftItemBinding
import com.example.listviewtest.databinding.MsgRightItemBinding


class MsgAdapter(val msgList: List<Msg>) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {


    inner class LeftViewHolder(binding: MsgLeftItemBinding) : RecyclerView.ViewHolder(binding.root) {
        val leftMsg: TextView = binding.leftMsg

    }
    inner class RightViewHolder(binding: MsgRightItemBinding) : RecyclerView.ViewHolder(binding.root) {
        val rightMsg: TextView = binding.rightMsg
    }

    override fun getItemViewType(position: Int): Int {
        return msgList[position].type
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder  = if(viewType == Msg.TYPE_RECEIVED){
            val inflate = MsgLeftItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
            LeftViewHolder(inflate)
        }else{
            val inflate = MsgRightItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
            RightViewHolder(inflate)
        }


    override fun getItemCount()= msgList.size

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val msg = msgList[position]
        when(holder){
            is LeftViewHolder -> holder.leftMsg.text = msg.content
            is RightViewHolder -> holder.rightMsg.text = msg.content
            else -> throw  IllegalArgumentException()
        }
    }
}